// API 使用示例
// 展示如何在各个页面中使用 petHouseAPI

// 1. 登录页面使用示例
async function handleLogin() {
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    
    try {
        const response = await petHouseAPI.auth.login({
            email,
            password
        });
        
        // 保存token和用户信息
        localStorage.setItem('token', response.token);
        localStorage.setItem('userInfo', JSON.stringify(response.user));
        
        // 跳转到首页
        window.location.href = '/index.html';
        
    } catch (error) {
        console.error('登录失败:', error);
    }
}

// 2. 注册页面使用示例
async function handleRegister() {
    const formData = {
        username: document.getElementById('username').value,
        email: document.getElementById('email').value,
        password: document.getElementById('password').value,
        phone: document.getElementById('phone').value
    };
    
    try {
        const response = await petHouseAPI.auth.register(formData);
        alert('注册成功！请登录');
        window.location.href = '/login.html';
        
    } catch (error) {
        console.error('注册失败:', error);
    }
}

// 3. 宠物管理页面使用示例
async function loadPets() {
    try {
        const pets = await petHouseAPI.pets.getAll();
        displayPets(pets);
    } catch (error) {
        console.error('获取宠物列表失败:', error);
    }
}

async function addPet() {
    const petData = {
        name: document.getElementById('petName').value,
        type: document.getElementById('petType').value,
        breed: document.getElementById('petBreed').value,
        age: document.getElementById('petAge').value,
        weight: document.getElementById('petWeight').value
    };
    
    try {
        const newPet = await petHouseAPI.pets.create(petData);
        alert('宠物添加成功！');
        loadPets(); // 重新加载宠物列表
    } catch (error) {
        console.error('添加宠物失败:', error);
    }
}

// 4. 服务页面使用示例
async function loadServices() {
    try {
        const services = await petHouseAPI.services.getAll();
        displayServices(services);
    } catch (error) {
        console.error('获取服务列表失败:', error);
    }
}

async function searchServices(keyword) {
    try {
        const services = await petHouseAPI.services.search(keyword);
        displayServices(services);
    } catch (error) {
        console.error('搜索服务失败:', error);
    }
}

// 5. 订单页面使用示例
async function loadOrders() {
    try {
        const orders = await petHouseAPI.orders.getAll({
            page: 1,
            limit: 10,
            status: 'all'
        });
        displayOrders(orders);
    } catch (error) {
        console.error('获取订单列表失败:', error);
    }
}

async function createOrder(serviceId, petId, scheduleData) {
    const orderData = {
        serviceId,
        petId,
        schedule: scheduleData,
        notes: document.getElementById('orderNotes').value
    };
    
    try {
        const order = await petHouseAPI.orders.create(orderData);
        alert('订单创建成功！');
        window.location.href = `/order-detail.html?id=${order.id}`;
    } catch (error) {
        console.error('创建订单失败:', error);
    }
}

// 6. 用户资料页面使用示例
async function loadUserProfile() {
    try {
        const profile = await petHouseAPI.user.getProfile();
        displayProfile(profile);
    } catch (error) {
        console.error('获取用户资料失败:', error);
    }
}

async function updateUserProfile() {
    const profileData = {
        username: document.getElementById('username').value,
        phone: document.getElementById('phone').value,
        address: document.getElementById('address').value
    };
    
    try {
        const updatedProfile = await petHouseAPI.user.updateProfile(profileData);
        alert('资料更新成功！');
        loadUserProfile(); // 重新加载资料
    } catch (error) {
        console.error('更新资料失败:', error);
    }
}

// 7. 文件上传示例
async function uploadPetPhoto(petId, fileInput) {
    const file = fileInput.files[0];
    if (!file) {
        alert('请选择文件');
        return;
    }
    
    try {
        const result = await petHouseAPI.pets.uploadPhoto(petId, file);
        alert('照片上传成功！');
        // 更新宠物照片显示
        updatePetPhoto(petId, result.photoUrl);
    } catch (error) {
        console.error('上传照片失败:', error);
    }
}

// 8. 支付示例
async function handlePayment(orderId, paymentMethod) {
    const paymentData = {
        method: paymentMethod,
        amount: document.getElementById('amount').value
    };
    
    try {
        const payment = await petHouseAPI.orders.pay(orderId, paymentData);
        alert('支付成功！');
        window.location.href = `/order-detail.html?id=${orderId}`;
    } catch (error) {
        console.error('支付失败:', error);
    }
}

// 9. 登出示例
async function handleLogout() {
    try {
        await petHouseAPI.auth.logout();
        // 清除本地存储
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        // 跳转到登录页
        window.location.href = '/login.html';
    } catch (error) {
        console.error('登出失败:', error);
        // 即使API调用失败，也要清除本地数据
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        window.location.href = '/login.html';
    }
}

// 10. 检查登录状态
function checkAuthStatus() {
    const token = localStorage.getItem('token');
    if (!token) {
        // 如果不在登录页面，则跳转到登录页
        if (!window.location.pathname.includes('login.html') && 
            !window.location.pathname.includes('register.html')) {
            window.location.href = '/login.html';
        }
        return false;
    }
    return true;
}

// 11. 页面初始化时检查登录状态
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkAuthStatus();
    
    // 根据当前页面加载相应的数据
    const currentPage = window.location.pathname;
    
    if (currentPage.includes('pets.html')) {
        loadPets();
    } else if (currentPage.includes('services.html')) {
        loadServices();
    } else if (currentPage.includes('orders.html')) {
        loadOrders();
    } else if (currentPage.includes('profile.html')) {
        loadUserProfile();
    }
});

// 辅助函数示例
function displayPets(pets) {
    const container = document.getElementById('petsContainer');
    if (!container) return;
    
    container.innerHTML = pets.map(pet => `
        <div class="pet-card">
            <h3>${pet.name}</h3>
            <p>类型: ${pet.type}</p>
            <p>品种: ${pet.breed}</p>
            <p>年龄: ${pet.age}岁</p>
            <button onclick="editPet(${pet.id})">编辑</button>
            <button onclick="deletePet(${pet.id})">删除</button>
        </div>
    `).join('');
}

function displayServices(services) {
    const container = document.getElementById('servicesContainer');
    if (!container) return;
    
    container.innerHTML = services.map(service => `
        <div class="service-card">
            <h3>${service.name}</h3>
            <p>${service.description}</p>
            <p>价格: ¥${service.price}</p>
            <button onclick="bookService(${service.id})">预约服务</button>
        </div>
    `).join('');
}

function displayOrders(orders) {
    const container = document.getElementById('ordersContainer');
    if (!container) return;
    
    container.innerHTML = orders.map(order => `
        <div class="order-card">
            <h3>订单号: ${order.orderNumber}</h3>
            <p>服务: ${order.serviceName}</p>
            <p>状态: ${order.status}</p>
            <p>金额: ¥${order.amount}</p>
            <button onclick="viewOrderDetail(${order.id})">查看详情</button>
        </div>
    `).join('');
}

function displayProfile(profile) {
    document.getElementById('username').value = profile.username || '';
    document.getElementById('email').value = profile.email || '';
    document.getElementById('phone').value = profile.phone || '';
    document.getElementById('address').value = profile.address || '';
} 